package com.loobot.album.config.secure.gateway;

import com.loobot.album.exception.AppException;
import com.loobot.album.net.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: Ike.Fan
 * @date: 2019/2/27.
 */
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    LoobotToken loobotToken;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        String loobot_header = request.getHeader("loobot_header");
        LoobotAccount loobotAccount;
        if(StringUtils.isEmpty(loobot_header)||  (loobotAccount =loobotToken.verifyToken(loobot_header))==null){
            throw AppException.getException(ErrorCode.NEED_AUTHORD);
        }
        PartnerThreadLocal.set(loobotAccount);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        PartnerThreadLocal.set(null);
    }
}
